package com.guangwei.learnchinesecharacter

import android.annotation.SuppressLint
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import kotlinx.android.synthetic.main.activity_words_list_maintain.*
import java.io.BufferedReader
import java.io.InputStreamReader

class WordsListMaintain : AppCompatActivity() {
    private var itemList=ArrayList<String>()
    private var adapter :MyAdapter?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_words_list_maintain)
        initView()
        initListView()
    }

    private fun initListView(){
        itemList.clear()
        // TO-DO: Add the init data to the list below
        loadData()
        adapter = MyAdapter(itemList,this)
        listView.adapter = adapter
    }

    private fun addListView(word: String){
        itemList.add(word)
        adapter = MyAdapter(itemList,this)
        listView.adapter = adapter
        storeData()
    }

    private fun delAllListView(){
        itemList.clear()
        adapter = MyAdapter(itemList,this)
        listView.adapter = adapter
        storeData()
    }

    @SuppressLint("InflateParams")
    private fun initView(){

        btn_add_name.setOnClickListener{
            val lay = layoutInflater.inflate(R.layout.dialog_box_add_words,null)
            val dialogBuilder = AlertDialog.Builder(this)
            val dialog = dialogBuilder.setTitle(R.string.prompt_input_words).setView(lay).create()
            dialog.show()

            lay.findViewById<Button>(R.id.btn_ok).setOnClickListener{
                val word = lay.findViewById<EditText>(R.id.et_name).text.toString()
                addListView(word)
                initListView()  // This is workaround, we would like one line show in one list item
                dialog.dismiss()
            }

            lay.findViewById<Button>(R.id.btn_cancel).setOnClickListener{
                dialog.dismiss()
            }

        }

        btn_del_name.setOnClickListener{
            val alertDialog = AlertDialog.Builder(this)
                .setTitle(R.string.warning)
                .setMessage(R.string.prompt_del_all_words)
                .setPositiveButton(R.string.OK) { dialog, which ->
                    delAllListView()
                    dialog.dismiss()
                }
                .setNegativeButton(R.string.Cancel) { dialog, which -> dialog.dismiss() }

            alertDialog.show()
        }
    }

    private fun loadData() {
        try {
            val fileInputStream = openFileInput("data.txt")

            //把文件内容读取进缓冲读取器（use方法会自动对BufferedReader进行关闭）
            BufferedReader(InputStreamReader(fileInputStream)).use {
                var line: String
                itemList.clear()
                while (true) {
                    line = it.readLine() ?: break //当有内容时读取一行数据，否则退出循环
                    println(line) //打印一行数据
                    itemList.add(line)
                    adapter = MyAdapter(itemList,this)
                    listView.adapter = adapter
                }
            }
        } catch (throwable: Throwable) {
            // 捕获到异常的处理
        }

    }

    private fun storeData() {
        val fileOutput = openFileOutput("data.txt", Activity.MODE_PRIVATE)

        for (word in itemList) {
            println(word)
            fileOutput.write((word+'\n').toByteArray(Charsets.UTF_8))
        }

        fileOutput.close()
        Toast.makeText(this, "数据保存成功！", Toast.LENGTH_LONG).show()
    }



}
